#include "GLUtils.h"

using namespace game_engine::open_gl;

///////////////////////////////////////////////////////////////////////////////
// Constructors and Destructors
///////////////////////////////////////////////////////////////////////////////

GLUtils::GLUtils(void)
{
}

GLUtils::~GLUtils(void)
{
}

///////////////////////////////////////////////////////////////////////////////
// Other public methods
///////////////////////////////////////////////////////////////////////////////

void GLUtils::mainInit(int argc, char** argv, const string &title,
                                void (*render)(void),
                                void (*readKey)(UCHAR, INT32, INT32),
                                void (*readSpecialKey)(INT32, INT32, INT32),
                                void (*readKeyUp)(UCHAR, INT32, INT32),
                                void (*readSpecialKeyUp)(INT32, INT32, INT32),
                                void (*readMouse)(INT32, INT32, INT32, INT32),
                                void (*loop)(void))
{
	//GLUT initialization
	glutInit(&argc, argv);

	//RGBA with double buffer
	glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE);

	//Create centered window
	INT32 res_x = glutGet(GLUT_SCREEN_WIDTH);
	INT32 res_y = glutGet(GLUT_SCREEN_HEIGHT);
	INT32 pos_x = (res_x>>1)-(GAME_WIDTH>>1);
	INT32 pos_y = (res_y>>1)-(GAME_HEIGHT>>1);
	
	glutInitWindowPosition(pos_x,pos_y);
	glutInitWindowSize(GAME_WIDTH,GAME_HEIGHT);
	glutCreateWindow(title.c_str());

	//Register callback functions
    glutDisplayFunc(render);			
    glutKeyboardFunc(readKey);		
	glutSpecialFunc(readSpecialKey);	
    glutKeyboardUpFunc(readKeyUp);		
	glutSpecialUpFunc(readSpecialKeyUp);	
    glutMouseFunc(readMouse);
	glutIdleFunc(loop);
}

void GLUtils::commonLevelInit(void)
{
	// Alpha test enabled
	glAlphaFunc(GL_GREATER, 0.05f);
	glEnable(GL_ALPHA_TEST);

	//Textures enabled
	glEnable(GL_TEXTURE_2D);
}

void GLUtils::levelInit(const FLOAT32 width, const FLOAT32 height)
{
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, static_cast<GLfloat>(width), 0, static_cast<GLfloat>(height), 
        0, 1);
	glMatrixMode(GL_MODELVIEW);
}

void GLUtils::initializeRendering(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();
}

void GLUtils::finalizeRendering(void)
{
    glutSwapBuffers();
}

void GLUtils::startEventLoop(void)
{
    glutMainLoop();	
}

void GLUtils::repaint(void)
{
    glutPostRedisplay();
}
